import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/views/home/model/salesman.dart';
import 'package:yuan_hang_app/widget/w_text.dart';

import '../../../../base/custom_appbar.dart';
import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_colors.dart';
import '../../../../res/w_dimens.dart';
import '../../../../widget/custom_search.dart';
import '../../../../widget/w_list_view.dart';
import '../../../../widget/w_toast.dart';


enum OperateType {
  snatchClue,     //抢线索
  allocationClue, //线索分配, 战败审核再分配
  activationClue  //线索激活
}


class AdviserSelectPage extends StatefulWidget {
  final OperateType type;
  final int? entrance;  //店长批量分配线索:1 , 战败审核再分配:2
  final int? clueId;
  final List<int>? clueIds;
  const AdviserSelectPage({super.key, required this.type, this.clueId, this.clueIds, this.entrance});

  @override
  BaseState<AdviserSelectPage> createState() => _AdviserSelectPageState();
}

class _AdviserSelectPageState extends BaseState<AdviserSelectPage> {

  List<Salesman> dataList = [];
  int selectedIndex = -1;

  Future<Null> _refresh() async {
    showLoading();
    fetchDataList();
  }

  Map<String, dynamic> queryParams = {"needFollowTimes": true, "nameOrPhone":null,};

  @override
  void initState() {
    super.initState();
    showLoading();
    fetchDataList();
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "选择顾问",
        child: Column(
          children: [
            CustomSearch(hintText: "销售顾问名称/手机号", onTextChange: (text){
              queryParams["nameOrPhone"] = text;
              CommonUtils.antiShake(fetchDataList);
            }, showSort: false,),
            SizedBox(height: 10.px,),
            Expanded(
              child: RefreshIndicator(
                onRefresh: _refresh,
                child: ListView.builder(
                  padding: EdgeInsets.zero,
                  itemBuilder: _listItem,
                  itemCount: dataList.length,
                )
              ),
            ),
            GestureDetector(
              onTap: () {
                if(dataList.every((item) => item.isSelected == false)) {
                  Toast.toast("请先选择销售顾问");
                  return;
                }
                CommonUtils.throttle(allocationClues);
              },
              child: Container(
                margin: EdgeInsets.only(
                    top: 16.px, left: 24.px, right: 24.px, bottom: 16.px),
                width: SizeUtils.screenW() - 48.px,
                alignment: Alignment.center,
                height: 48.px,
                decoration: BoxDecoration(
                  color: WColors.primaryColor,
                  borderRadius: BorderRadius.circular(24.px),
                ),
                child: WText(
                  "确定",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.px,
                  ),
                ),
              ),
            ),
          ],
        )
    );
  }

  allocationClues() {
    Salesman salesman = dataList[selectedIndex];
    Map params = {};
    String postUrl = "";
    if (widget.type == OperateType.snatchClue) {
      params = {"id" : widget.clueId, "saleman" : salesman.userId, "salemanName" : salesman.userName};
      postUrl = Api.snatchClue;
    } else if (widget.type == OperateType.allocationClue) {
      params = {"idList" : widget.clueIds, "saleman" : salesman.userId, "salemanName" : salesman.userName, "entrance" : widget.entrance};
      postUrl = Api.allocationClue;
    } else {
      params = {"clueIdList" : widget.clueIds, "saleman" : salesman.userId};
      postUrl = Api.activationClue;
    }
    showLoading();
    HttpUtils().post(postUrl, data: params).then((value){
      hideLoading();
      if (value.resultCode == 200) {
        Toast.toast("分配成功");
        RouteHelper.maybePop(context,true);
      } else {
        Toast.toast(value.errMsg);
      }
    });
  }


  void fetchDataList() {
    dataList = [];
    HttpUtils().post(Api.getSalesmanList2, data: queryParams).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          List data = value.data ?? [];
          List<Salesman> list = data.map((item) => Salesman.fromJson(item)).toList();
          setState(() {
            dataList = list;
          });
        }
      } else {

      }
    }).catchError((e){
      hideLoading();
    });
  }

  Widget _listItem(context,index) {
    Salesman item = dataList[index];
    return GestureDetector(
      onTap: (){
        setState(() {
          selectedIndex = index;
          item.isSelected = selectedIndex == index;
        });
      },
      child: Container(
        decoration: BoxDecoration(boxShadow: [
          BoxShadow(
              color: WColors.CDFEFFB,
              offset: const Offset(0, 1),
              blurRadius: 3.px)
        ], borderRadius: BorderRadius.circular(10.px), color: Colors.white),
        margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 10.px),
        padding: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 10.px),
        child: Row(
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 10.px,),
                Row(
                  children: [
                    WText(item.userName ?? "",style: TextStyle(
                        fontSize: WDimens.tsMedium,
                        color:  WColors.mainTextColor),),
                    SizedBox(width: 40.px,),
                    WText(
                      "待跟进线索量: ${item.followTimes}",
                      style: TextStyle(fontSize: WDimens.tsMedium, color:  WColors.mainTextColor),
                    )
                  ],
                ),
                SizedBox(height: 10.px,),
                WText(item.userPhone ?? "",style: TextStyle(
                    fontSize: WDimens.tsMedium,
                    color:  WColors.mainTextColor),)
              ],
            ),
            Expanded(child: Container()),
            Padding(
              padding: EdgeInsets.only(right: 10.px),
              child: selectedIndex == index
                  ?  Image.asset("images/ic_checked_circle.png",
                color: WColors.primaryColor,width: 25.px,)
                  : Image.asset("images/ic_check_circle.png",
                color: WColors.primaryColor,width: 25.px,),
            )
          ],
        ),
      ),
    );
  }
}